package org.firecloud.h5fun.controller.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.javabean.UserBean;
import org.json.JSONObject;
/**
 * 上传原创Project的Zip压缩文件Ajax方法调用URL：ajax_upload_project_zip_file<br>
 * 必须登陆：true<br>
 * 必须管理：true<br>
 * 参数：<br>
 * zipFile，必须，上传的Zip文件<br>
 * 注：无<br>
 * @author fc
 */
@MultipartConfig
public class AjaxUploadProjectZipFile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		try {
			UserBean loginUser = (UserBean) req.getSession().getAttribute("loginUser");
			if (loginUser != null && loginUser.isAdmin()) {
				resp.setCharacterEncoding("UTF-8");
				resp.setContentType("application/json");
				String pathname = req.getServletContext().getRealPath("/files/apps/");
				String dirName = String.format("%d", System.currentTimeMillis());
				Part part = req.getPart("zipFile");
				ZipInputStream zipInputStream = new ZipInputStream(part.getInputStream());
				ZipEntry ze = null;
				byte[] ch = new byte[1024];
				int fileSum = 0;
				while ((ze = zipInputStream.getNextEntry()) != null) {
					File zfile = new File(pathname + "/" + dirName + "/" + ze.getName());
					File fpath = new File(zfile.getParentFile().getPath());
					if (ze.isDirectory()) {
						if (!zfile.exists())
							zfile.mkdirs();
						zipInputStream.closeEntry();
					} else {
						if (!fpath.exists())
							fpath.mkdirs();
						FileOutputStream fouts = new FileOutputStream(zfile);
						int i;
						while ((i = zipInputStream.read(ch)) != -1) {
							fouts.write(ch, 0, i);
						}
						zipInputStream.closeEntry();
						fouts.close();
						fileSum++;
					}
				}
				zipInputStream.close();
				json.put("type", 0);
				json.put("dirName", dirName);
				json.put("fileSum", fileSum);
			} else {
				json.put("type", -2);
				json.put("msg", "权限不足");
			}
		} catch (Exception e) {
			json.put("type", -1);
			json.put("msg", e.getMessage());
			e.printStackTrace();
			Logger.getRootLogger().error(e);
		}
		resp.getWriter().print(json);
	}
}
